<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>How to use sessions &mdash; Django 1.7.8.dev20150401230226 documentation</title>
    
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../../',
        VERSION:     '1.7.8.dev20150401230226',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <link rel="top" title="Django 1.7.8.dev20150401230226 documentation" href="../../index.html" />
    <link rel="up" title="Handling HTTP requests" href="index.html" />
    <link rel="next" title="Working with forms" href="../forms/index.html" />
    <link rel="prev" title="Middleware" href="middleware.html" />



 
<script type="text/javascript" src="../../templatebuiltins.js"></script>
<script type="text/javascript">
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);
</script>


  </head>
  <body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 1.7.8.dev20150401230226 documentation</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="middleware.html" title="Middleware">previous</a>
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="../forms/index.html" title="Working with forms">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="topics-http-sessions">
            
  <div class="section" id="s-module-django.contrib.sessions">
<span id="s-how-to-use-sessions"></span><span id="module-django.contrib.sessions"></span><span id="how-to-use-sessions"></span><h1>How to use sessions<a class="headerlink" href="#module-django.contrib.sessions" title="Permalink to this headline">¶</a></h1>
<p>Django provides full support for anonymous sessions. The session framework
lets you store and retrieve arbitrary data on a per-site-visitor basis. It
stores data on the server side and abstracts the sending and receiving of
cookies. Cookies contain a session ID &#8211; not the data itself (unless you&#8217;re
using the <a class="reference internal" href="#cookie-session-backend"><em>cookie based backend</em></a>).</p>
<div class="section" id="s-enabling-sessions">
<span id="enabling-sessions"></span><h2>Enabling sessions<a class="headerlink" href="#enabling-sessions" title="Permalink to this headline">¶</a></h2>
<p>Sessions are implemented via a piece of <a class="reference internal" href="../../ref/middleware.html"><em>middleware</em></a>.</p>
<p>To enable session functionality, do the following:</p>
<ul class="simple">
<li>Edit the <a class="reference internal" href="../../ref/settings.html#std:setting-MIDDLEWARE_CLASSES"><tt class="xref std std-setting docutils literal"><span class="pre">MIDDLEWARE_CLASSES</span></tt></a> setting and make sure
it contains <tt class="docutils literal"><span class="pre">'django.contrib.sessions.middleware.SessionMiddleware'</span></tt>.
The default <tt class="docutils literal"><span class="pre">settings.py</span></tt> created by <tt class="docutils literal"><span class="pre">django-admin.py</span> <span class="pre">startproject</span></tt>
has <tt class="docutils literal"><span class="pre">SessionMiddleware</span></tt> activated.</li>
</ul>
<p>If you don&#8217;t want to use sessions, you might as well remove the
<tt class="docutils literal"><span class="pre">SessionMiddleware</span></tt> line from <a class="reference internal" href="../../ref/settings.html#std:setting-MIDDLEWARE_CLASSES"><tt class="xref std std-setting docutils literal"><span class="pre">MIDDLEWARE_CLASSES</span></tt></a> and
<tt class="docutils literal"><span class="pre">'django.contrib.sessions'</span></tt> from your <a class="reference internal" href="../../ref/settings.html#std:setting-INSTALLED_APPS"><tt class="xref std std-setting docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a>.
It&#8217;ll save you a small bit of overhead.</p>
</div>
<div class="section" id="s-configuring-the-session-engine">
<span id="s-configuring-sessions"></span><span id="configuring-the-session-engine"></span><span id="configuring-sessions"></span><h2>Configuring the session engine<a class="headerlink" href="#configuring-the-session-engine" title="Permalink to this headline">¶</a></h2>
<p>By default, Django stores sessions in your database (using the model
<tt class="docutils literal"><span class="pre">django.contrib.sessions.models.Session</span></tt>). Though this is convenient, in
some setups it&#8217;s faster to store session data elsewhere, so Django can be
configured to store session data on your filesystem or in your cache.</p>
<div class="section" id="s-using-database-backed-sessions">
<span id="using-database-backed-sessions"></span><h3>Using database-backed sessions<a class="headerlink" href="#using-database-backed-sessions" title="Permalink to this headline">¶</a></h3>
<p>If you want to use a database-backed session, you need to add
<tt class="docutils literal"><span class="pre">'django.contrib.sessions'</span></tt> to your <a class="reference internal" href="../../ref/settings.html#std:setting-INSTALLED_APPS"><tt class="xref std std-setting docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a> setting.</p>
<p>Once you have configured your installation, run <tt class="docutils literal"><span class="pre">manage.py</span> <span class="pre">migrate</span></tt>
to install the single database table that stores session data.</p>
</div>
<div class="section" id="s-using-cached-sessions">
<span id="s-cached-sessions-backend"></span><span id="using-cached-sessions"></span><span id="cached-sessions-backend"></span><h3>Using cached sessions<a class="headerlink" href="#using-cached-sessions" title="Permalink to this headline">¶</a></h3>
<p>For better performance, you may want to use a cache-based session backend.</p>
<p>To store session data using Django&#8217;s cache system, you&#8217;ll first need to make
sure you&#8217;ve configured your cache; see the <a class="reference internal" href="../cache.html"><em>cache documentation</em></a> for details.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">You should only use cache-based sessions if you&#8217;re using the Memcached
cache backend. The local-memory cache backend doesn&#8217;t retain data long
enough to be a good choice, and it&#8217;ll be faster to use file or database
sessions directly instead of sending everything through the file or
database cache backends. Additionally, the local-memory cache backend is
NOT multi-process safe, therefore probably not a good choice for production
environments.</p>
</div>
<p>If you have multiple caches defined in <a class="reference internal" href="../../ref/settings.html#std:setting-CACHES"><tt class="xref std std-setting docutils literal"><span class="pre">CACHES</span></tt></a>, Django will use the
default cache. To use another cache, set <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_CACHE_ALIAS"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_CACHE_ALIAS</span></tt></a> to the
name of that cache.</p>
<p>Once your cache is configured, you&#8217;ve got two choices for how to store data in
the cache:</p>
<ul class="simple">
<li>Set <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_ENGINE"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_ENGINE</span></tt></a> to
<tt class="docutils literal"><span class="pre">&quot;django.contrib.sessions.backends.cache&quot;</span></tt> for a simple caching session
store. Session data will be stored directly in your cache. However, session
data may not be persistent: cached data can be evicted if the cache fills
up or if the cache server is restarted.</li>
<li>For persistent, cached data, set <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_ENGINE"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_ENGINE</span></tt></a> to
<tt class="docutils literal"><span class="pre">&quot;django.contrib.sessions.backends.cached_db&quot;</span></tt>. This uses a
write-through cache &#8211; every write to the cache will also be written to
the database. Session reads only use the database if the data is not
already in the cache.</li>
</ul>
<p>Both session stores are quite fast, but the simple cache is faster because it
disregards persistence. In most cases, the <tt class="docutils literal"><span class="pre">cached_db</span></tt> backend will be fast
enough, but if you need that last bit of performance, and are willing to let
session data be expunged from time to time, the <tt class="docutils literal"><span class="pre">cache</span></tt> backend is for you.</p>
<p>If you use the <tt class="docutils literal"><span class="pre">cached_db</span></tt> session backend, you also need to follow the
configuration instructions for the <a class="reference internal" href="#using-database-backed-sessions">using database-backed sessions</a>.</p>
<div class="versionchanged">
<span class="title">Changed in Django 1.7:</span> <p>Before version 1.7, the <tt class="docutils literal"><span class="pre">cached_db</span></tt> backend always used the <tt class="docutils literal"><span class="pre">default</span></tt>
cache rather than the <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_CACHE_ALIAS"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_CACHE_ALIAS</span></tt></a>.</p>
</div>
</div>
<div class="section" id="s-using-file-based-sessions">
<span id="using-file-based-sessions"></span><h3>Using file-based sessions<a class="headerlink" href="#using-file-based-sessions" title="Permalink to this headline">¶</a></h3>
<p>To use file-based sessions, set the <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_ENGINE"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_ENGINE</span></tt></a> setting to
<tt class="docutils literal"><span class="pre">&quot;django.contrib.sessions.backends.file&quot;</span></tt>.</p>
<p>You might also want to set the <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_FILE_PATH"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_FILE_PATH</span></tt></a> setting (which
defaults to output from <tt class="docutils literal"><span class="pre">tempfile.gettempdir()</span></tt>, most likely <tt class="docutils literal"><span class="pre">/tmp</span></tt>) to
control where Django stores session files. Be sure to check that your Web
server has permissions to read and write to this location.</p>
</div>
<div class="section" id="s-using-cookie-based-sessions">
<span id="s-cookie-session-backend"></span><span id="using-cookie-based-sessions"></span><span id="cookie-session-backend"></span><h3>Using cookie-based sessions<a class="headerlink" href="#using-cookie-based-sessions" title="Permalink to this headline">¶</a></h3>
<p>To use cookies-based sessions, set the <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_ENGINE"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_ENGINE</span></tt></a> setting to
<tt class="docutils literal"><span class="pre">&quot;django.contrib.sessions.backends.signed_cookies&quot;</span></tt>. The session data will be
stored using Django&#8217;s tools for <a class="reference internal" href="../signing.html"><em>cryptographic signing</em></a>
and the <a class="reference internal" href="../../ref/settings.html#std:setting-SECRET_KEY"><tt class="xref std std-setting docutils literal"><span class="pre">SECRET_KEY</span></tt></a> setting.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">It&#8217;s recommended to leave the <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_COOKIE_HTTPONLY"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_COOKIE_HTTPONLY</span></tt></a> setting
on <tt class="docutils literal"><span class="pre">True</span></tt> to prevent access to the stored data from JavaScript.</p>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p><strong>If the SECRET_KEY is not kept secret and you are using the</strong>
<a class="reference internal" href="#django.contrib.sessions.serializers.PickleSerializer" title="django.contrib.sessions.serializers.PickleSerializer"><tt class="xref py py-class docutils literal"><span class="pre">PickleSerializer</span></tt></a>, <strong>this can
lead to arbitrary remote code execution.</strong></p>
<p>An attacker in possession of the <a class="reference internal" href="../../ref/settings.html#std:setting-SECRET_KEY"><tt class="xref std std-setting docutils literal"><span class="pre">SECRET_KEY</span></tt></a> can not only
generate falsified session data, which your site will trust, but also
remotely execute arbitrary code, as the data is serialized using pickle.</p>
<p>If you use cookie-based sessions, pay extra care that your secret key is
always kept completely secret, for any system which might be remotely
accessible.</p>
<p><strong>The session data is signed but not encrypted</strong></p>
<p>When using the cookies backend the session data can be read by the client.</p>
<p>A MAC (Message Authentication Code) is used to protect the data against
changes by the client, so that the session data will be invalidated when being
tampered with. The same invalidation happens if the client storing the
cookie (e.g. your user&#8217;s browser) can&#8217;t store all of the session cookie and
drops data. Even though Django compresses the data, it&#8217;s still entirely
possible to exceed the <a class="reference external" href="http://tools.ietf.org/html/rfc2965#section-5.3">common limit of 4096 bytes</a> per cookie.</p>
<p><strong>No freshness guarantee</strong></p>
<p>Note also that while the MAC can guarantee the authenticity of the data
(that it was generated by your site, and not someone else), and the
integrity of the data (that it is all there and correct), it cannot
guarantee freshness i.e. that you are being sent back the last thing you
sent to the client. This means that for some uses of session data, the
cookie backend might open you up to <a class="reference external" href="http://en.wikipedia.org/wiki/Replay_attack">replay attacks</a>. Unlike other session
backends which keep a server-side record of each session and invalidate it
when a user logs out, cookie-based sessions are not invalidated when a user
logs out. Thus if an attacker steals a user&#8217;s cookie, they can use that
cookie to login as that user even if the user logs out. Cookies will only
be detected as &#8216;stale&#8217; if they are older than your
<a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_COOKIE_AGE"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_COOKIE_AGE</span></tt></a>.</p>
<p><strong>Performance</strong></p>
<p class="last">Finally, the size of a cookie can have an impact on the <a class="reference external" href="http://yuiblog.com/blog/2007/03/01/performance-research-part-3/">speed of your site</a>.</p>
</div>
</div>
</div>
<div class="section" id="s-using-sessions-in-views">
<span id="using-sessions-in-views"></span><h2>Using sessions in views<a class="headerlink" href="#using-sessions-in-views" title="Permalink to this headline">¶</a></h2>
<p>When <tt class="docutils literal"><span class="pre">SessionMiddleware</span></tt> is activated, each <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><tt class="xref py py-class docutils literal"><span class="pre">HttpRequest</span></tt></a>
object &#8211; the first argument to any Django view function &#8211; will have a
<tt class="docutils literal"><span class="pre">session</span></tt> attribute, which is a dictionary-like object.</p>
<p>You can read it and write to <tt class="docutils literal"><span class="pre">request.session</span></tt> at any point in your view.
You can edit it multiple times.</p>
<dl class="class">
<dt id="django.contrib.sessions.backends.base.SessionBase">
<em class="property">class </em><tt class="descclassname">backends.base.</tt><tt class="descname">SessionBase</tt><a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase" title="Permalink to this definition">¶</a></dt>
<dd><p>This is the base class for all session objects. It has the following
standard dictionary methods:</p>
<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.__getitem__">
<tt class="descname">__getitem__</tt>(<em>key</em>)<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.__getitem__" title="Permalink to this definition">¶</a></dt>
<dd><p>Example: <tt class="docutils literal"><span class="pre">fav_color</span> <span class="pre">=</span> <span class="pre">request.session['fav_color']</span></tt></p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.__setitem__">
<tt class="descname">__setitem__</tt>(<em>key</em>, <em>value</em>)<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.__setitem__" title="Permalink to this definition">¶</a></dt>
<dd><p>Example: <tt class="docutils literal"><span class="pre">request.session['fav_color']</span> <span class="pre">=</span> <span class="pre">'blue'</span></tt></p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.__delitem__">
<tt class="descname">__delitem__</tt>(<em>key</em>)<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.__delitem__" title="Permalink to this definition">¶</a></dt>
<dd><p>Example: <tt class="docutils literal"><span class="pre">del</span> <span class="pre">request.session['fav_color']</span></tt>. This raises <tt class="docutils literal"><span class="pre">KeyError</span></tt>
if the given <tt class="docutils literal"><span class="pre">key</span></tt> isn&#8217;t already in the session.</p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.__contains__">
<tt class="descname">__contains__</tt>(<em>key</em>)<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.__contains__" title="Permalink to this definition">¶</a></dt>
<dd><p>Example: <tt class="docutils literal"><span class="pre">'fav_color'</span> <span class="pre">in</span> <span class="pre">request.session</span></tt></p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.get">
<tt class="descname">get</tt>(<em>key</em>, <em>default=None</em>)<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.get" title="Permalink to this definition">¶</a></dt>
<dd><p>Example: <tt class="docutils literal"><span class="pre">fav_color</span> <span class="pre">=</span> <span class="pre">request.session.get('fav_color',</span> <span class="pre">'red')</span></tt></p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.pop">
<tt class="descname">pop</tt>(<em>key</em>)<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.pop" title="Permalink to this definition">¶</a></dt>
<dd><p>Example: <tt class="docutils literal"><span class="pre">fav_color</span> <span class="pre">=</span> <span class="pre">request.session.pop('fav_color')</span></tt></p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.keys">
<tt class="descname">keys</tt>()<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.keys" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.items">
<tt class="descname">items</tt>()<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.items" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.setdefault">
<tt class="descname">setdefault</tt>()<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.setdefault" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.clear">
<tt class="descname">clear</tt>()<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.clear" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>It also has these methods:</p>
<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.flush">
<tt class="descname">flush</tt>()<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.flush" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete the current session data from the session and regenerate the
session key value that is sent back to the user in the cookie. This is
used if you want to ensure that the previous session data can&#8217;t be
accessed again from the user&#8217;s browser (for example, the
<a class="reference internal" href="../auth/default.html#django.contrib.auth.logout" title="django.contrib.auth.logout"><tt class="xref py py-func docutils literal"><span class="pre">django.contrib.auth.logout()</span></tt></a> function calls it).</p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.set_test_cookie">
<tt class="descname">set_test_cookie</tt>()<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.set_test_cookie" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets a test cookie to determine whether the user&#8217;s browser supports
cookies. Due to the way cookies work, you won&#8217;t be able to test this
until the user&#8217;s next page request. See <a class="reference internal" href="#setting-test-cookies">Setting test cookies</a> below for
more information.</p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.test_cookie_worked">
<tt class="descname">test_cookie_worked</tt>()<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.test_cookie_worked" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns either <tt class="docutils literal"><span class="pre">True</span></tt> or <tt class="docutils literal"><span class="pre">False</span></tt>, depending on whether the user&#8217;s
browser accepted the test cookie. Due to the way cookies work, you&#8217;ll
have to call <tt class="docutils literal"><span class="pre">set_test_cookie()</span></tt> on a previous, separate page request.
See <a class="reference internal" href="#setting-test-cookies">Setting test cookies</a> below for more information.</p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.delete_test_cookie">
<tt class="descname">delete_test_cookie</tt>()<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.delete_test_cookie" title="Permalink to this definition">¶</a></dt>
<dd><p>Deletes the test cookie. Use this to clean up after yourself.</p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.set_expiry">
<tt class="descname">set_expiry</tt>(<em>value</em>)<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.set_expiry" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets the expiration time for the session. You can pass a number of
different values:</p>
<ul class="simple">
<li>If <tt class="docutils literal"><span class="pre">value</span></tt> is an integer, the session will expire after that
many seconds of inactivity. For example, calling
<tt class="docutils literal"><span class="pre">request.session.set_expiry(300)</span></tt> would make the session expire
in 5 minutes.</li>
<li>If <tt class="docutils literal"><span class="pre">value</span></tt> is a <tt class="docutils literal"><span class="pre">datetime</span></tt> or <tt class="docutils literal"><span class="pre">timedelta</span></tt> object, the
session will expire at that specific date/time. Note that <tt class="docutils literal"><span class="pre">datetime</span></tt>
and <tt class="docutils literal"><span class="pre">timedelta</span></tt> values are only serializable if you are using the
<a class="reference internal" href="#django.contrib.sessions.serializers.PickleSerializer" title="django.contrib.sessions.serializers.PickleSerializer"><tt class="xref py py-class docutils literal"><span class="pre">PickleSerializer</span></tt></a>.</li>
<li>If <tt class="docutils literal"><span class="pre">value</span></tt> is <tt class="docutils literal"><span class="pre">0</span></tt>, the user&#8217;s session cookie will expire
when the user&#8217;s Web browser is closed.</li>
<li>If <tt class="docutils literal"><span class="pre">value</span></tt> is <tt class="docutils literal"><span class="pre">None</span></tt>, the session reverts to using the global
session expiry policy.</li>
</ul>
<p>Reading a session is not considered activity for expiration
purposes. Session expiration is computed from the last time the
session was <em>modified</em>.</p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.get_expiry_age">
<tt class="descname">get_expiry_age</tt>()<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.get_expiry_age" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the number of seconds until this session expires. For sessions
with no custom expiration (or those set to expire at browser close), this
will equal <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_COOKIE_AGE"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_COOKIE_AGE</span></tt></a>.</p>
<p>This function accepts two optional keyword arguments:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">modification</span></tt>: last modification of the session, as a
<a class="reference external" href="http://docs.python.org/3/library/datetime.html#datetime.datetime" title="(in Python v3.4)"><tt class="xref py py-class docutils literal"><span class="pre">datetime</span></tt></a> object. Defaults to the current time.</li>
<li><tt class="docutils literal"><span class="pre">expiry</span></tt>: expiry information for the session, as a
<a class="reference external" href="http://docs.python.org/3/library/datetime.html#datetime.datetime" title="(in Python v3.4)"><tt class="xref py py-class docutils literal"><span class="pre">datetime</span></tt></a> object, an <a class="reference external" href="http://docs.python.org/3/library/functions.html#int" title="(in Python v3.4)"><tt class="xref py py-class docutils literal"><span class="pre">int</span></tt></a> (in seconds), or
<tt class="docutils literal"><span class="pre">None</span></tt>. Defaults to the value stored in the session by
<a class="reference internal" href="#django.contrib.sessions.backends.base.SessionBase.set_expiry" title="django.contrib.sessions.backends.base.SessionBase.set_expiry"><tt class="xref py py-meth docutils literal"><span class="pre">set_expiry()</span></tt></a>, if there is one, or <tt class="docutils literal"><span class="pre">None</span></tt>.</li>
</ul>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.get_expiry_date">
<tt class="descname">get_expiry_date</tt>()<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.get_expiry_date" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the date this session will expire. For sessions with no custom
expiration (or those set to expire at browser close), this will equal the
date <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_COOKIE_AGE"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_COOKIE_AGE</span></tt></a> seconds from now.</p>
<p>This function accepts the same keyword arguments as <a class="reference internal" href="#django.contrib.sessions.backends.base.SessionBase.get_expiry_age" title="django.contrib.sessions.backends.base.SessionBase.get_expiry_age"><tt class="xref py py-meth docutils literal"><span class="pre">get_expiry_age()</span></tt></a>.</p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.get_expire_at_browser_close">
<tt class="descname">get_expire_at_browser_close</tt>()<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.get_expire_at_browser_close" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns either <tt class="docutils literal"><span class="pre">True</span></tt> or <tt class="docutils literal"><span class="pre">False</span></tt>, depending on whether the user&#8217;s
session cookie will expire when the user&#8217;s Web browser is closed.</p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.clear_expired">
<tt class="descname">clear_expired</tt>()<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.clear_expired" title="Permalink to this definition">¶</a></dt>
<dd><p>Removes expired sessions from the session store. This class method is
called by <a class="reference internal" href="../../ref/django-admin.html#django-admin-clearsessions"><tt class="xref std std-djadmin docutils literal"><span class="pre">clearsessions</span></tt></a>.</p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.cycle_key">
<tt class="descname">cycle_key</tt>()<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.cycle_key" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a new session key while retaining the current session data.
<a class="reference internal" href="../auth/default.html#django.contrib.auth.login" title="django.contrib.auth.login"><tt class="xref py py-func docutils literal"><span class="pre">django.contrib.auth.login()</span></tt></a> calls this method to mitigate against
session fixation.</p>
</dd></dl>

</dd></dl>

<div class="section" id="s-session-serialization">
<span id="s-id1"></span><span id="session-serialization"></span><span id="id1"></span><h3>Session serialization<a class="headerlink" href="#session-serialization" title="Permalink to this headline">¶</a></h3>
<div class="versionchanged">
<span class="title">Changed in Django 1.6.</span> </div>
<p>Before version 1.6, Django defaulted to using <a class="reference external" href="http://docs.python.org/3/library/pickle.html#module-pickle" title="(in Python v3.4)"><tt class="xref py py-mod docutils literal"><span class="pre">pickle</span></tt></a> to serialize
session data before storing it in the backend. If you&#8217;re using the <a class="reference internal" href="#cookie-session-backend"><em>signed
cookie session backend</em></a> and <a class="reference internal" href="../../ref/settings.html#std:setting-SECRET_KEY"><tt class="xref std std-setting docutils literal"><span class="pre">SECRET_KEY</span></tt></a> is
known by an attacker (there isn&#8217;t an inherent vulnerability in Django that
would cause it to leak), the attacker could insert a string into their session
which, when unpickled, executes arbitrary code on the server. The technique for
doing so is simple and easily available on the internet. Although the cookie
session storage signs the cookie-stored data to prevent tampering, a
<a class="reference internal" href="../../ref/settings.html#std:setting-SECRET_KEY"><tt class="xref std std-setting docutils literal"><span class="pre">SECRET_KEY</span></tt></a> leak immediately escalates to a remote code execution
vulnerability.</p>
<p>This attack can be mitigated by serializing session data using JSON rather
than <a class="reference external" href="http://docs.python.org/3/library/pickle.html#module-pickle" title="(in Python v3.4)"><tt class="xref py py-mod docutils literal"><span class="pre">pickle</span></tt></a>. To facilitate this, Django 1.5.3 introduced a new setting,
<a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_SERIALIZER"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_SERIALIZER</span></tt></a>, to customize the session serialization format.
For backwards compatibility, this setting defaults to
using <a class="reference internal" href="#django.contrib.sessions.serializers.PickleSerializer" title="django.contrib.sessions.serializers.PickleSerializer"><tt class="xref py py-class docutils literal"><span class="pre">django.contrib.sessions.serializers.PickleSerializer</span></tt></a> in
Django 1.5.x, but, for security hardening, defaults to
<a class="reference internal" href="#django.contrib.sessions.serializers.JSONSerializer" title="django.contrib.sessions.serializers.JSONSerializer"><tt class="xref py py-class docutils literal"><span class="pre">django.contrib.sessions.serializers.JSONSerializer</span></tt></a> in Django 1.6.
Even with the caveats described in <a class="reference internal" href="#custom-serializers"><em>Write Your Own Serializer</em></a>, we highly
recommend sticking with JSON serialization <em>especially if you are using the
cookie backend</em>.</p>
<div class="section" id="s-bundled-serializers">
<span id="bundled-serializers"></span><h4>Bundled Serializers<a class="headerlink" href="#bundled-serializers" title="Permalink to this headline">¶</a></h4>
<dl class="class">
<dt id="django.contrib.sessions.serializers.JSONSerializer">
<em class="property">class </em><tt class="descclassname">serializers.</tt><tt class="descname">JSONSerializer</tt><a class="headerlink" href="#django.contrib.sessions.serializers.JSONSerializer" title="Permalink to this definition">¶</a></dt>
<dd><p>A wrapper around the JSON serializer from <a class="reference internal" href="../signing.html#module-django.core.signing" title="django.core.signing: Django's signing framework."><tt class="xref py py-mod docutils literal"><span class="pre">django.core.signing</span></tt></a>. Can
only serialize basic data types.</p>
<p>In addition, as JSON supports only string keys, note that using non-string
keys in <tt class="docutils literal"><span class="pre">request.session</span></tt> won&#8217;t work as expected:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="c"># initial assignment</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="s">&#39;bar&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c"># subsequent requests following serialization &amp; deserialization</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c"># of session data</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>  <span class="c"># KeyError</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s">&#39;0&#39;</span><span class="p">]</span>
<span class="go">&#39;bar&#39;</span>
</pre></div>
</div>
<p>See the <a class="reference internal" href="#custom-serializers"><em>Write Your Own Serializer</em></a> section for more details on limitations
of JSON serialization.</p>
</dd></dl>

<dl class="class">
<dt id="django.contrib.sessions.serializers.PickleSerializer">
<em class="property">class </em><tt class="descclassname">serializers.</tt><tt class="descname">PickleSerializer</tt><a class="headerlink" href="#django.contrib.sessions.serializers.PickleSerializer" title="Permalink to this definition">¶</a></dt>
<dd><p>Supports arbitrary Python objects, but, as described above, can lead to a
remote code execution vulnerability if <a class="reference internal" href="../../ref/settings.html#std:setting-SECRET_KEY"><tt class="xref std std-setting docutils literal"><span class="pre">SECRET_KEY</span></tt></a> becomes known
by an attacker.</p>
</dd></dl>

</div>
<div class="section" id="s-write-your-own-serializer">
<span id="s-custom-serializers"></span><span id="write-your-own-serializer"></span><span id="custom-serializers"></span><h4>Write Your Own Serializer<a class="headerlink" href="#write-your-own-serializer" title="Permalink to this headline">¶</a></h4>
<p>Note that unlike <a class="reference internal" href="#django.contrib.sessions.serializers.PickleSerializer" title="django.contrib.sessions.serializers.PickleSerializer"><tt class="xref py py-class docutils literal"><span class="pre">PickleSerializer</span></tt></a>,
the <a class="reference internal" href="#django.contrib.sessions.serializers.JSONSerializer" title="django.contrib.sessions.serializers.JSONSerializer"><tt class="xref py py-class docutils literal"><span class="pre">JSONSerializer</span></tt></a> cannot handle
arbitrary Python data types. As is often the case, there is a trade-off between
convenience and security. If you wish to store more advanced data types
including <tt class="docutils literal"><span class="pre">datetime</span></tt> and <tt class="docutils literal"><span class="pre">Decimal</span></tt> in JSON backed sessions, you will need
to write a custom serializer (or convert such values to a JSON serializable
object before storing them in <tt class="docutils literal"><span class="pre">request.session</span></tt>). While serializing these
values is fairly straightforward
(<tt class="docutils literal"><span class="pre">django.core.serializers.json.DateTimeAwareJSONEncoder</span></tt> may be helpful),
writing a decoder that can reliably get back the same thing that you put in is
more fragile. For example, you run the risk of returning a <tt class="docutils literal"><span class="pre">datetime</span></tt> that
was actually a string that just happened to be in the same format chosen for
<tt class="docutils literal"><span class="pre">datetime</span></tt>s).</p>
<p>Your serializer class must implement two methods,
<tt class="docutils literal"><span class="pre">dumps(self,</span> <span class="pre">obj)</span></tt> and <tt class="docutils literal"><span class="pre">loads(self,</span> <span class="pre">data)</span></tt>, to serialize and deserialize
the dictionary of session data, respectively.</p>
</div>
</div>
<div class="section" id="s-session-object-guidelines">
<span id="session-object-guidelines"></span><h3>Session object guidelines<a class="headerlink" href="#session-object-guidelines" title="Permalink to this headline">¶</a></h3>
<ul class="simple">
<li>Use normal Python strings as dictionary keys on <tt class="docutils literal"><span class="pre">request.session</span></tt>. This
is more of a convention than a hard-and-fast rule.</li>
<li>Session dictionary keys that begin with an underscore are reserved for
internal use by Django.</li>
<li>Don&#8217;t override <tt class="docutils literal"><span class="pre">request.session</span></tt> with a new object, and don&#8217;t access or
set its attributes. Use it like a Python dictionary.</li>
</ul>
</div>
<div class="section" id="s-examples">
<span id="examples"></span><h3>Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h3>
<p>This simplistic view sets a <tt class="docutils literal"><span class="pre">has_commented</span></tt> variable to <tt class="docutils literal"><span class="pre">True</span></tt> after a user
posts a comment. It doesn&#8217;t let a user post a comment more than once:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">post_comment</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">new_comment</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">&#39;has_commented&#39;</span><span class="p">,</span> <span class="bp">False</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s">&quot;You&#39;ve already commented.&quot;</span><span class="p">)</span>
    <span class="n">c</span> <span class="o">=</span> <span class="n">comments</span><span class="o">.</span><span class="n">Comment</span><span class="p">(</span><span class="n">comment</span><span class="o">=</span><span class="n">new_comment</span><span class="p">)</span>
    <span class="n">c</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
    <span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s">&#39;has_commented&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="bp">True</span>
    <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s">&#39;Thanks for your comment!&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>This simplistic view logs in a &#8220;member&#8221; of the site:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">login</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="n">m</span> <span class="o">=</span> <span class="n">Member</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">username</span><span class="o">=</span><span class="n">request</span><span class="o">.</span><span class="n">POST</span><span class="p">[</span><span class="s">&#39;username&#39;</span><span class="p">])</span>
    <span class="k">if</span> <span class="n">m</span><span class="o">.</span><span class="n">password</span> <span class="o">==</span> <span class="n">request</span><span class="o">.</span><span class="n">POST</span><span class="p">[</span><span class="s">&#39;password&#39;</span><span class="p">]:</span>
        <span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s">&#39;member_id&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">m</span><span class="o">.</span><span class="n">id</span>
        <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s">&quot;You&#39;re logged in.&quot;</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s">&quot;Your username and password didn&#39;t match.&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>...And this one logs a member out, according to <tt class="docutils literal"><span class="pre">login()</span></tt> above:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">logout</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="k">del</span> <span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s">&#39;member_id&#39;</span><span class="p">]</span>
    <span class="k">except</span> <span class="ne">KeyError</span><span class="p">:</span>
        <span class="k">pass</span>
    <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s">&quot;You&#39;re logged out.&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>The standard <a class="reference internal" href="../auth/default.html#django.contrib.auth.logout" title="django.contrib.auth.logout"><tt class="xref py py-meth docutils literal"><span class="pre">django.contrib.auth.logout()</span></tt></a> function actually does a bit
more than this to prevent inadvertent data leakage. It calls the
<a class="reference internal" href="#django.contrib.sessions.backends.base.SessionBase.flush" title="django.contrib.sessions.backends.base.SessionBase.flush"><tt class="xref py py-meth docutils literal"><span class="pre">flush()</span></tt></a> method of <tt class="docutils literal"><span class="pre">request.session</span></tt>.
We are using this example as a demonstration of how to work with session
objects, not as a full <tt class="docutils literal"><span class="pre">logout()</span></tt> implementation.</p>
</div>
</div>
<div class="section" id="s-setting-test-cookies">
<span id="setting-test-cookies"></span><h2>Setting test cookies<a class="headerlink" href="#setting-test-cookies" title="Permalink to this headline">¶</a></h2>
<p>As a convenience, Django provides an easy way to test whether the user&#8217;s
browser accepts cookies. Just call the
<a class="reference internal" href="#django.contrib.sessions.backends.base.SessionBase.set_test_cookie" title="django.contrib.sessions.backends.base.SessionBase.set_test_cookie"><tt class="xref py py-meth docutils literal"><span class="pre">set_test_cookie()</span></tt></a> method of
<tt class="docutils literal"><span class="pre">request.session</span></tt> in a view, and call
<a class="reference internal" href="#django.contrib.sessions.backends.base.SessionBase.test_cookie_worked" title="django.contrib.sessions.backends.base.SessionBase.test_cookie_worked"><tt class="xref py py-meth docutils literal"><span class="pre">test_cookie_worked()</span></tt></a> in a subsequent view &#8211;
not in the same view call.</p>
<p>This awkward split between <tt class="docutils literal"><span class="pre">set_test_cookie()</span></tt> and <tt class="docutils literal"><span class="pre">test_cookie_worked()</span></tt>
is necessary due to the way cookies work. When you set a cookie, you can&#8217;t
actually tell whether a browser accepted it until the browser&#8217;s next request.</p>
<p>It&#8217;s good practice to use
<a class="reference internal" href="#django.contrib.sessions.backends.base.SessionBase.delete_test_cookie" title="django.contrib.sessions.backends.base.SessionBase.delete_test_cookie"><tt class="xref py py-meth docutils literal"><span class="pre">delete_test_cookie()</span></tt></a> to clean up after
yourself. Do this after you&#8217;ve verified that the test cookie worked.</p>
<p>Here&#8217;s a typical usage example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">login</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">request</span><span class="o">.</span><span class="n">method</span> <span class="o">==</span> <span class="s">&#39;POST&#39;</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="o">.</span><span class="n">test_cookie_worked</span><span class="p">():</span>
            <span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="o">.</span><span class="n">delete_test_cookie</span><span class="p">()</span>
            <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s">&quot;You&#39;re logged in.&quot;</span><span class="p">)</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s">&quot;Please enable cookies and try again.&quot;</span><span class="p">)</span>
    <span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="o">.</span><span class="n">set_test_cookie</span><span class="p">()</span>
    <span class="k">return</span> <span class="n">render_to_response</span><span class="p">(</span><span class="s">&#39;foo/login_form.html&#39;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="s-using-sessions-out-of-views">
<span id="using-sessions-out-of-views"></span><h2>Using sessions out of views<a class="headerlink" href="#using-sessions-out-of-views" title="Permalink to this headline">¶</a></h2>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>The examples in this section import the <tt class="docutils literal"><span class="pre">SessionStore</span></tt> object directly
from the <tt class="docutils literal"><span class="pre">django.contrib.sessions.backends.db</span></tt> backend. In your own code,
you should consider importing <tt class="docutils literal"><span class="pre">SessionStore</span></tt> from the session engine
designated by <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_ENGINE"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_ENGINE</span></tt></a>, as below:</p>
<div class="last highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">importlib</span> <span class="kn">import</span> <span class="n">import_module</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.conf</span> <span class="kn">import</span> <span class="n">settings</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">SessionStore</span> <span class="o">=</span> <span class="n">import_module</span><span class="p">(</span><span class="n">settings</span><span class="o">.</span><span class="n">SESSION_ENGINE</span><span class="p">)</span><span class="o">.</span><span class="n">SessionStore</span>
</pre></div>
</div>
</div>
<p>An API is available to manipulate session data outside of a view:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.contrib.sessions.backends.db</span> <span class="kn">import</span> <span class="n">SessionStore</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">SessionStore</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c"># stored as seconds since epoch since datetimes are not serializable in JSON.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="p">[</span><span class="s">&#39;last_login&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1376587691</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">session_key</span>
<span class="go">&#39;2b1189a188b44ad18c35e113ac6ceead&#39;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">SessionStore</span><span class="p">(</span><span class="n">session_key</span><span class="o">=</span><span class="s">&#39;2b1189a188b44ad18c35e113ac6ceead&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="p">[</span><span class="s">&#39;last_login&#39;</span><span class="p">]</span>
<span class="go">1376587691</span>
</pre></div>
</div>
<p>In order to mitigate session fixation attacks, sessions keys that don&#8217;t exist
are regenerated:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.contrib.sessions.backends.db</span> <span class="kn">import</span> <span class="n">SessionStore</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">SessionStore</span><span class="p">(</span><span class="n">session_key</span><span class="o">=</span><span class="s">&#39;no-such-session-here&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">session_key</span>
<span class="go">&#39;ff882814010ccbc3c870523934fee5a2&#39;</span>
</pre></div>
</div>
<p>If you&#8217;re using the <tt class="docutils literal"><span class="pre">django.contrib.sessions.backends.db</span></tt> backend, each
session is just a normal Django model. The <tt class="docutils literal"><span class="pre">Session</span></tt> model is defined in
<tt class="docutils literal"><span class="pre">django/contrib/sessions/models.py</span></tt>. Because it&#8217;s a normal model, you can
access sessions using the normal Django database API:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.contrib.sessions.models</span> <span class="kn">import</span> <span class="n">Session</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">Session</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="s">&#39;2b1189a188b44ad18c35e113ac6ceead&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">expire_date</span>
<span class="go">datetime.datetime(2005, 8, 20, 13, 35, 12)</span>
</pre></div>
</div>
<p>Note that you&#8217;ll need to call <tt class="docutils literal"><span class="pre">get_decoded()</span></tt> to get the session dictionary.
This is necessary because the dictionary is stored in an encoded format:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">session_data</span>
<span class="go">&#39;KGRwMQpTJ19hdXRoX3VzZXJfaWQnCnAyCkkxCnMuMTExY2ZjODI2Yj...&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">get_decoded</span><span class="p">()</span>
<span class="go">{&#39;user_id&#39;: 42}</span>
</pre></div>
</div>
</div>
<div class="section" id="s-when-sessions-are-saved">
<span id="when-sessions-are-saved"></span><h2>When sessions are saved<a class="headerlink" href="#when-sessions-are-saved" title="Permalink to this headline">¶</a></h2>
<p>By default, Django only saves to the session database when the session has been
modified &#8211; that is if any of its dictionary values have been assigned or
deleted:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># Session is modified.</span>
<span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s">&#39;foo&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s">&#39;bar&#39;</span>

<span class="c"># Session is modified.</span>
<span class="k">del</span> <span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s">&#39;foo&#39;</span><span class="p">]</span>

<span class="c"># Session is modified.</span>
<span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s">&#39;foo&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="p">{}</span>

<span class="c"># Gotcha: Session is NOT modified, because this alters</span>
<span class="c"># request.session[&#39;foo&#39;] instead of request.session.</span>
<span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s">&#39;foo&#39;</span><span class="p">][</span><span class="s">&#39;bar&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s">&#39;baz&#39;</span>
</pre></div>
</div>
<p>In the last case of the above example, we can tell the session object
explicitly that it has been modified by setting the <tt class="docutils literal"><span class="pre">modified</span></tt> attribute on
the session object:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="o">.</span><span class="n">modified</span> <span class="o">=</span> <span class="bp">True</span>
</pre></div>
</div>
<p>To change this default behavior, set the <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_SAVE_EVERY_REQUEST"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_SAVE_EVERY_REQUEST</span></tt></a>
setting to <tt class="docutils literal"><span class="pre">True</span></tt>. When set to <tt class="docutils literal"><span class="pre">True</span></tt>, Django will save the session to the
database on every single request.</p>
<p>Note that the session cookie is only sent when a session has been created or
modified. If <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_SAVE_EVERY_REQUEST"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_SAVE_EVERY_REQUEST</span></tt></a> is <tt class="docutils literal"><span class="pre">True</span></tt>, the session
cookie will be sent on every request.</p>
<p>Similarly, the <tt class="docutils literal"><span class="pre">expires</span></tt> part of a session cookie is updated each time the
session cookie is sent.</p>
<p>The session is not saved if the response&#8217;s status code is 500.</p>
</div>
<div class="section" id="s-browser-length-sessions-vs-persistent-sessions">
<span id="s-browser-length-vs-persistent-sessions"></span><span id="browser-length-sessions-vs-persistent-sessions"></span><span id="browser-length-vs-persistent-sessions"></span><h2>Browser-length sessions vs. persistent sessions<a class="headerlink" href="#browser-length-sessions-vs-persistent-sessions" title="Permalink to this headline">¶</a></h2>
<p>You can control whether the session framework uses browser-length sessions vs.
persistent sessions with the <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_EXPIRE_AT_BROWSER_CLOSE"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_EXPIRE_AT_BROWSER_CLOSE</span></tt></a>
setting.</p>
<p>By default, <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_EXPIRE_AT_BROWSER_CLOSE"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_EXPIRE_AT_BROWSER_CLOSE</span></tt></a> is set to <tt class="docutils literal"><span class="pre">False</span></tt>,
which means session cookies will be stored in users&#8217; browsers for as long as
<a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_COOKIE_AGE"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_COOKIE_AGE</span></tt></a>. Use this if you don&#8217;t want people to have to
log in every time they open a browser.</p>
<p>If <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_EXPIRE_AT_BROWSER_CLOSE"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_EXPIRE_AT_BROWSER_CLOSE</span></tt></a> is set to <tt class="docutils literal"><span class="pre">True</span></tt>, Django will
use browser-length cookies &#8211; cookies that expire as soon as the user closes
their browser. Use this if you want people to have to log in every time they
open a browser.</p>
<p>This setting is a global default and can be overwritten at a per-session level
by explicitly calling the <a class="reference internal" href="#django.contrib.sessions.backends.base.SessionBase.set_expiry" title="django.contrib.sessions.backends.base.SessionBase.set_expiry"><tt class="xref py py-meth docutils literal"><span class="pre">set_expiry()</span></tt></a> method
of <tt class="docutils literal"><span class="pre">request.session</span></tt> as described above in <a class="reference internal" href="#using-sessions-in-views">using sessions in views</a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Some browsers (Chrome, for example) provide settings that allow users to
continue browsing sessions after closing and re-opening the browser. In
some cases, this can interfere with the
<a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_EXPIRE_AT_BROWSER_CLOSE"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_EXPIRE_AT_BROWSER_CLOSE</span></tt></a> setting and prevent sessions
from expiring on browser close. Please be aware of this while testing
Django applications which have the
<a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_EXPIRE_AT_BROWSER_CLOSE"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_EXPIRE_AT_BROWSER_CLOSE</span></tt></a> setting enabled.</p>
</div>
</div>
<div class="section" id="s-clearing-the-session-store">
<span id="clearing-the-session-store"></span><h2>Clearing the session store<a class="headerlink" href="#clearing-the-session-store" title="Permalink to this headline">¶</a></h2>
<p>As users create new sessions on your website, session data can accumulate in
your session store. If you&#8217;re using the database backend, the
<tt class="docutils literal"><span class="pre">django_session</span></tt> database table will grow. If you&#8217;re using the file backend,
your temporary directory will contain an increasing number of files.</p>
<p>To understand this problem, consider what happens with the database backend.
When a user logs in, Django adds a row to the <tt class="docutils literal"><span class="pre">django_session</span></tt> database
table. Django updates this row each time the session data changes. If the user
logs out manually, Django deletes the row. But if the user does <em>not</em> log out,
the row never gets deleted. A similar process happens with the file backend.</p>
<p>Django does <em>not</em> provide automatic purging of expired sessions. Therefore,
it&#8217;s your job to purge expired sessions on a regular basis. Django provides a
clean-up management command for this purpose: <a class="reference internal" href="../../ref/django-admin.html#django-admin-clearsessions"><tt class="xref std std-djadmin docutils literal"><span class="pre">clearsessions</span></tt></a>. It&#8217;s
recommended to call this command on a regular basis, for example as a daily
cron job.</p>
<p>Note that the cache backend isn&#8217;t vulnerable to this problem, because caches
automatically delete stale data. Neither is the cookie backend, because the
session data is stored by the users&#8217; browsers.</p>
</div>
<div class="section" id="s-settings">
<span id="settings"></span><h2>Settings<a class="headerlink" href="#settings" title="Permalink to this headline">¶</a></h2>
<p>A few <a class="reference internal" href="../../ref/settings.html#settings-sessions"><em>Django settings</em></a> give you control over session
behavior:</p>
<ul class="simple">
<li><a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_CACHE_ALIAS"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_CACHE_ALIAS</span></tt></a></li>
<li><a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_COOKIE_AGE"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_COOKIE_AGE</span></tt></a></li>
<li><a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_COOKIE_DOMAIN"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_COOKIE_DOMAIN</span></tt></a></li>
<li><a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_COOKIE_HTTPONLY"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_COOKIE_HTTPONLY</span></tt></a></li>
<li><a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_COOKIE_NAME"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_COOKIE_NAME</span></tt></a></li>
<li><a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_COOKIE_PATH"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_COOKIE_PATH</span></tt></a></li>
<li><a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_COOKIE_SECURE"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_COOKIE_SECURE</span></tt></a></li>
<li><a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_ENGINE"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_ENGINE</span></tt></a></li>
<li><a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_EXPIRE_AT_BROWSER_CLOSE"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_EXPIRE_AT_BROWSER_CLOSE</span></tt></a></li>
<li><a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_FILE_PATH"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_FILE_PATH</span></tt></a></li>
<li><a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_SAVE_EVERY_REQUEST"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_SAVE_EVERY_REQUEST</span></tt></a></li>
</ul>
</div>
<div class="section" id="s-session-security">
<span id="s-topics-session-security"></span><span id="session-security"></span><span id="topics-session-security"></span><h2>Session security<a class="headerlink" href="#session-security" title="Permalink to this headline">¶</a></h2>
<p>Subdomains within a site are able to set cookies on the client for the whole
domain. This makes session fixation possible if cookies are permitted from
subdomains not controlled by trusted users.</p>
<p>For example, an attacker could log into <tt class="docutils literal"><span class="pre">good.example.com</span></tt> and get a valid
session for their account. If the attacker has control over <tt class="docutils literal"><span class="pre">bad.example.com</span></tt>,
they can use it to send their session key to you since a subdomain is permitted
to set cookies on <tt class="docutils literal"><span class="pre">*.example.com</span></tt>. When you visit <tt class="docutils literal"><span class="pre">good.example.com</span></tt>,
you&#8217;ll be logged in as the attacker and might inadvertently enter your
sensitive personal data (e.g. credit card info) into the attackers account.</p>
<p>Another possible attack would be if <tt class="docutils literal"><span class="pre">good.example.com</span></tt> sets its
<a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_COOKIE_DOMAIN"><tt class="xref std std-setting docutils literal"><span class="pre">SESSION_COOKIE_DOMAIN</span></tt></a>&nbsp;to <tt class="docutils literal"><span class="pre">&quot;.example.com&quot;</span></tt> which would cause
session cookies from that site to be sent to <tt class="docutils literal"><span class="pre">bad.example.com</span></tt>.</p>
</div>
<div class="section" id="s-technical-details">
<span id="technical-details"></span><h2>Technical details<a class="headerlink" href="#technical-details" title="Permalink to this headline">¶</a></h2>
<ul class="simple">
<li>The session dictionary accepts any <a class="reference external" href="http://docs.python.org/3/library/json.html#module-json" title="(in Python v3.4)"><tt class="xref py py-mod docutils literal"><span class="pre">json</span></tt></a> serializable value when using
<a class="reference internal" href="#django.contrib.sessions.serializers.JSONSerializer" title="django.contrib.sessions.serializers.JSONSerializer"><tt class="xref py py-class docutils literal"><span class="pre">JSONSerializer</span></tt></a> or any
pickleable Python object when using
<a class="reference internal" href="#django.contrib.sessions.serializers.PickleSerializer" title="django.contrib.sessions.serializers.PickleSerializer"><tt class="xref py py-class docutils literal"><span class="pre">PickleSerializer</span></tt></a>. See the
<a class="reference external" href="http://docs.python.org/3/library/pickle.html#module-pickle" title="(in Python v3.4)"><tt class="xref py py-mod docutils literal"><span class="pre">pickle</span></tt></a> module for more information.</li>
<li>Session data is stored in a database table named <tt class="docutils literal"><span class="pre">django_session</span></tt> .</li>
<li>Django only sends a cookie if it needs to. If you don&#8217;t set any session
data, it won&#8217;t send a session cookie.</li>
</ul>
</div>
<div class="section" id="s-session-ids-in-urls">
<span id="session-ids-in-urls"></span><h2>Session IDs in URLs<a class="headerlink" href="#session-ids-in-urls" title="Permalink to this headline">¶</a></h2>
<p>The Django sessions framework is entirely, and solely, cookie-based. It does
not fall back to putting session IDs in URLs as a last resort, as PHP does.
This is an intentional design decision. Not only does that behavior make URLs
ugly, it makes your site vulnerable to session-ID theft via the &#8220;Referer&#8221;
header.</p>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">How to use sessions</a><ul>
<li><a class="reference internal" href="#enabling-sessions">Enabling sessions</a></li>
<li><a class="reference internal" href="#configuring-the-session-engine">Configuring the session engine</a><ul>
<li><a class="reference internal" href="#using-database-backed-sessions">Using database-backed sessions</a></li>
<li><a class="reference internal" href="#using-cached-sessions">Using cached sessions</a></li>
<li><a class="reference internal" href="#using-file-based-sessions">Using file-based sessions</a></li>
<li><a class="reference internal" href="#using-cookie-based-sessions">Using cookie-based sessions</a></li>
</ul>
</li>
<li><a class="reference internal" href="#using-sessions-in-views">Using sessions in views</a><ul>
<li><a class="reference internal" href="#session-serialization">Session serialization</a><ul>
<li><a class="reference internal" href="#bundled-serializers">Bundled Serializers</a></li>
<li><a class="reference internal" href="#write-your-own-serializer">Write Your Own Serializer</a></li>
</ul>
</li>
<li><a class="reference internal" href="#session-object-guidelines">Session object guidelines</a></li>
<li><a class="reference internal" href="#examples">Examples</a></li>
</ul>
</li>
<li><a class="reference internal" href="#setting-test-cookies">Setting test cookies</a></li>
<li><a class="reference internal" href="#using-sessions-out-of-views">Using sessions out of views</a></li>
<li><a class="reference internal" href="#when-sessions-are-saved">When sessions are saved</a></li>
<li><a class="reference internal" href="#browser-length-sessions-vs-persistent-sessions">Browser-length sessions vs. persistent sessions</a></li>
<li><a class="reference internal" href="#clearing-the-session-store">Clearing the session store</a></li>
<li><a class="reference internal" href="#settings">Settings</a></li>
<li><a class="reference internal" href="#session-security">Session security</a></li>
<li><a class="reference internal" href="#technical-details">Technical details</a></li>
<li><a class="reference internal" href="#session-ids-in-urls">Session IDs in URLs</a></li>
</ul>
</li>
</ul>

  <h3>Browse</h3>
  <ul>
    
      <li>Prev: <a href="middleware.html">Middleware</a></li>
    
    
      <li>Next: <a href="../forms/index.html">Working with forms</a></li>
    
  </ul>
  <h3>You are here:</h3>
  <ul>
      <li>
        <a href="../../index.html">Django 1.7.8.dev20150401230226 documentation</a>
        
          <ul><li><a href="../index.html">Using Django</a>
        
          <ul><li><a href="index.html">Handling HTTP requests</a>
        
        <ul><li>How to use sessions</li></ul>
        </li></ul></li></ul>
      </li>
  </ul>

  <h3>This Page</h3>
  <ul class="this-page-menu">
    <li><a href="../../_sources/topics/http/sessions.txt"
           rel="nofollow">Show Source</a></li>
  </ul>
<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Apr 02, 2015</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="middleware.html" title="Middleware">previous</a>
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="../forms/index.html" title="Working with forms">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>